<template>
  <div class="login-container">
    <!-- 注册表单 -->
    <div v-if="isRegisterMode" class="login-form">
      <div class="header">
        <h1 class="title">📝 用户注册</h1>
        <p class="subtitle">创建您的账号密码管理账户</p>
      </div>

      <div class="register-form">
        <div class="input-group">
          <label class="input-label">用户名 *</label>
          <input
            class="input-field"
            v-model="registerForm.username"
            placeholder="请输入用户名(3-20位)"
            :maxlength="20"
          />
        </div>

        <div class="input-group">
          <label class="input-label">邮箱 *</label>
          <input
            class="input-field"
            type="email"
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            :maxlength="50"
          />
        </div>

        <div class="input-group">
          <label class="input-label">手机号 (可选)</label>
          <input
            class="input-field"
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            :maxlength="11"
          />
        </div>

        <div class="input-group">
          <label class="input-label">登录密码 *</label>
          <div class="password-input">
            <input
              class="input-field"
              v-model="registerForm.password"
              :type="showRegisterPassword ? 'text' : 'password'"
              placeholder="请输入登录密码(至少6位)"
              :maxlength="50"
            />
            <button
              type="button"
              class="password-toggle"
              @click="showRegisterPassword = !showRegisterPassword"
            >
              {{ showRegisterPassword ? '隐藏' : '显示' }}
            </button>
          </div>
        </div>

        <div class="input-group">
          <label class="input-label">主密码 *</label>
          <div class="password-input">
            <input
              class="input-field"
              v-model="registerForm.masterPassword"
              :type="showMasterPassword ? 'text' : 'password'"
              placeholder="请设置主密码(至少6位)"
              :maxlength="50"
            />
            <button
              type="button"
              class="password-toggle"
              @click="showMasterPassword = !showMasterPassword"
            >
              {{ showMasterPassword ? '隐藏' : '显示' }}
            </button>
          </div>
          <small class="hint">主密码用于加密所有账号数据,请务必牢记</small>
        </div>

        <div class="input-group">
          <label class="input-label">确认主密码 *</label>
          <input
            class="input-field"
            type="password"
            v-model="registerForm.confirmMasterPassword"
            placeholder="请再次输入主密码"
            :maxlength="50"
          />
          <small v-if="registerForm.confirmMasterPassword && registerForm.masterPassword !== registerForm.confirmMasterPassword" class="error-hint">
            ❌ 两次输入的主密码不一致
          </small>
          <small v-else-if="registerForm.confirmMasterPassword && registerForm.masterPassword === registerForm.confirmMasterPassword" class="success-hint">
            ✅ 主密码一致
          </small>
        </div>

        <div class="input-group">
          <label class="input-label">密码提示 (可选)</label>
          <input
            class="input-field"
            v-model="registerForm.passwordHint"
            placeholder="设置密码提示,帮助您记忆"
            :maxlength="100"
          />
        </div>

        <button
          class="login-btn"
          :disabled="!canRegister || isLoading"
          @click="handleRegister"
        >
          {{ isLoading ? '注册中...' : '立即注册' }}
        </button>

        <div class="actions">
          <button class="link" @click="backToLogin">已有账号? 返回登录</button>
        </div>
      </div>
    </div>

    <!-- 登录表单 -->
    <div v-else class="login-form">
      <!-- Logo和标题 -->
      <div class="header">
        <h1 class="title">🔐 账号密码管理器</h1>
        <p class="subtitle">安全便捷的多平台账号管理工具</p>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <div
          class="tab-item"
          :class="{ active: loginType === 'password' }"
          @click="switchLoginType('password')"
        >
          账号登录
        </div>
        <div
          class="tab-item"
          :class="{ active: loginType === 'oauth' }"
          @click="switchLoginType('oauth')"
        >
          快捷登录
        </div>
      </div>

      <!-- 账号密码登录 -->
      <div v-if="loginType === 'password'" class="password-login">
        <div class="input-group">
          <label class="input-label">用户名/手机号/邮箱</label>
          <input
            class="input-field"
            v-model="loginForm.login"
            placeholder="请输入用户名、手机号或邮箱"
            :maxlength="50"
          />
        </div>

        <div class="input-group">
          <label class="input-label">密码</label>
          <div class="password-input">
            <input
              class="input-field"
              v-model="loginForm.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              :maxlength="50"
            />
            <button
              type="button"
              class="password-toggle"
              @click="togglePassword"
            >
              {{ showPassword ? '隐藏' : '显示' }}
            </button>
          </div>
        </div>

        <button
          class="login-btn"
          :disabled="!canLogin || isLoading"
          @click="handlePasswordLogin"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </button>

        <div class="actions">
          <button class="link" @click="goToRegister">立即注册</button>
        </div>
      </div>

      <!-- 第三方登录 -->
      <div v-if="loginType === 'oauth'" class="oauth-login">
        <div class="oauth-buttons">
          <button class="oauth-btn wechat" @click="handleOAuthLogin('wechat')">
            <span class="icon">💬</span>
            微信登录
          </button>
          <button class="oauth-btn alipay" @click="handleOAuthLogin('alipay')">
            <span class="icon">💳</span>
            支付宝登录
          </button>
          <button class="oauth-btn douyin" @click="handleOAuthLogin('douyin')">
            <span class="icon">🎵</span>
            抖音登录
          </button>
        </div>

        <div class="oauth-tip">
          <p>首次使用将自动创建账号</p>
        </div>
      </div>

      <!-- 返回首页 -->
      <div class="actions">
        <router-link to="/" class="link">返回首页</router-link>
      </div>
    </div>

    <!-- 底部信息 -->
    <div class="footer">
      <p class="version">v1.0.0</p>
      <div class="links">
        <button class="link" @click="showPrivacy">隐私政策</button>
        <span class="separator">|</span>
        <button class="link" @click="showTerms">使用条款</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const loginType = ref<'password' | 'oauth'>('password')
const showPassword = ref(false)
const showRegisterPassword = ref(false)
const showMasterPassword = ref(false)
const isLoading = ref(false)
const isRegisterMode = ref(false)

// 登录表单
const loginForm = ref({
  login: '',
  password: ''
})

// 注册表单
const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  masterPassword: '',
  confirmMasterPassword: '',
  passwordHint: ''
})

// 计算属性
const canLogin = computed(() => {
  return loginForm.value.login.trim() && loginForm.value.password.trim()
})

const canRegister = computed(() => {
  const form = registerForm.value
  return (
    form.username.trim() &&
    form.email.trim() &&
    form.password.trim() &&
    form.masterPassword.trim() &&
    form.masterPassword === form.confirmMasterPassword &&
    form.masterPassword.length >= 6
  )
})

// 切换登录方式
const switchLoginType = (type: 'password' | 'oauth') => {
  loginType.value = type
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 获取设备信息
const getDeviceInfo = () => {
  const systemInfo = uni?.getSystemInfoSync?.() || {}

  return {
    device_id: generateDeviceId(),
    device_name: getDeviceName(systemInfo),
    platform: systemInfo.platform || 'h5',
    device_info: {
      brand: systemInfo.brand || 'Unknown',
      model: systemInfo.model || 'H5',
      system: systemInfo.system || navigator.platform,
      version: systemInfo.version || navigator.appVersion,
      screenWidth: systemInfo.screenWidth || window.screen.width,
      screenHeight: systemInfo.screenHeight || window.screen.height,
      pixelRatio: systemInfo.pixelRatio || window.devicePixelRatio || 1
    },
    encrypt_method: 'AES-256-GCM',
    app_version: '1.0.0'
  }
}

// 生成设备ID
const generateDeviceId = () => {
  // 尝试从localStorage获取现有设备ID
  let deviceId = localStorage.getItem('device_id')
  if (!deviceId) {
    // 生成新的设备ID
    const timestamp = Date.now().toString(36)
    const random = Math.random().toString(36).substr(2, 9)
    deviceId = `h5_${timestamp}_${random}`
    localStorage.setItem('device_id', deviceId)
  }
  return deviceId
}

// 获取设备名称
const getDeviceName = (systemInfo: any) => {
  if (systemInfo.model && systemInfo.model !== 'H5') {
    return systemInfo.model
  }

  const userAgent = navigator.userAgent
  if (userAgent.includes('Chrome')) {
    return 'Chrome浏览器'
  } else if (userAgent.includes('Firefox')) {
    return 'Firefox浏览器'
  } else if (userAgent.includes('Safari')) {
    return 'Safari浏览器'
  } else if (userAgent.includes('Edge')) {
    return 'Edge浏览器'
  }

  return 'H5浏览器'
}

// 账号密码登录
const handlePasswordLogin = async () => {
  try {
    isLoading.value = true

    // 获取设备信息
    const deviceInfo = getDeviceInfo()

    // 调用登录API
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        login: loginForm.value.login,
        password: loginForm.value.password,
        device_info: deviceInfo
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      // 保存token和用户信息
      localStorage.setItem('token', result.data.token)
      localStorage.setItem('userInfo', JSON.stringify(result.data.user))

      alert('登录成功！')
      // 跳转到仪表板
      router.push('/dashboard')
    } else {
      alert('登录失败: ' + result.message)
    }

  } catch (error) {
    console.error('登录错误:', error)
    alert('登录失败，请检查网络连接')
  } finally {
    isLoading.value = false
  }
}

// 第三方登录
const handleOAuthLogin = async (platform: 'wechat' | 'alipay' | 'douyin') => {
  try {
    isLoading.value = true

    const platformNames = {
      wechat: '微信',
      alipay: '支付宝',
      douyin: '抖音'
    }

    // 步骤1: 获取授权URL
    const response = await fetch(`/api/auth/${platform}-login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        device_info: getDeviceInfo(),
        redirect_uri: window.location.origin + '/oauth-callback'
      })
    })

    const result = await response.json()

    if (result.code === 200 && result.data.auth_url) {
      // 步骤2: 跳转到授权页面
      const authWindow = window.open(
        result.data.auth_url,
        `${platform}_oauth`,
        'width=600,height=700,left=200,top=100'
      )

      if (!authWindow) {
        alert('请允许弹出窗口以完成授权')
        isLoading.value = false
        return
      }

      // 步骤3: 监听授权回调
      const checkAuthStatus = setInterval(async () => {
        try {
          // 检查授权窗口是否关闭
          if (authWindow.closed) {
            clearInterval(checkAuthStatus)
            isLoading.value = false
            return
          }

          // 尝试读取授权窗口的URL(同域名才能读取)
          try {
            const authUrl = authWindow.location.href
            if (authUrl.includes('oauth-callback')) {
              const urlParams = new URLSearchParams(authWindow.location.search)
              const code = urlParams.get('code')
              const state = urlParams.get('state')

              if (code) {
                // 关闭授权窗口
                authWindow.close()
                clearInterval(checkAuthStatus)

                // 步骤4: 使用code完成登录
                await completeOAuthLogin(platform, code, state)
              }
            }
          } catch (e) {
            // 跨域时无法读取URL,忽略
          }
        } catch (error) {
          console.error('检查授权状态失败:', error)
        }
      }, 1000)

      // 5分钟后超时
      setTimeout(() => {
        clearInterval(checkAuthStatus)
        if (!authWindow.closed) {
          authWindow.close()
        }
        isLoading.value = false
      }, 300000)

    } else {
      alert(`获取${platformNames[platform]}授权失败: ` + (result.message || '未知错误'))
      isLoading.value = false
    }

  } catch (error) {
    console.error('第三方登录错误:', error)
    alert('登录失败,请重试')
    isLoading.value = false
  }
}

// 完成OAuth登录
const completeOAuthLogin = async (platform: string, code: string, state: string | null) => {
  try {
    const response = await fetch(`/api/auth/${platform}-login/callback`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        code,
        state,
        device_info: getDeviceInfo()
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      // 保存token和用户信息
      localStorage.setItem('token', result.data.token)
      localStorage.setItem('userInfo', JSON.stringify(result.data.user))

      alert('登录成功!')
      router.push('/dashboard')
    } else {
      alert('登录失败: ' + result.message)
    }

  } catch (error) {
    console.error('完成OAuth登录失败:', error)
    alert('登录失败,请重试')
  } finally {
    isLoading.value = false
  }
}

// 前往注册页
const goToRegister = () => {
  isRegisterMode.value = true
  // 清空表单
  registerForm.value = {
    username: '',
    email: '',
    phone: '',
    password: '',
    masterPassword: '',
    confirmMasterPassword: '',
    passwordHint: ''
  }
}

// 返回登录
const backToLogin = () => {
  isRegisterMode.value = false
}

// 处理注册
const handleRegister = async () => {
  if (!canRegister.value) {
    alert('请填写完整的注册信息')
    return
  }

  try {
    isLoading.value = true

    const response = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: registerForm.value.username,
        email: registerForm.value.email,
        phone: registerForm.value.phone || undefined,
        password: registerForm.value.password,
        master_password: registerForm.value.masterPassword,
        password_hint: registerForm.value.passwordHint || undefined,
        device_info: getDeviceInfo()
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      alert('注册成功!请登录')
      backToLogin()
      // 自动填充用户名
      loginForm.value.login = registerForm.value.username
    } else {
      alert('注册失败: ' + result.message)
    }

  } catch (error) {
    console.error('注册错误:', error)
    alert('注册失败,请检查网络连接')
  } finally {
    isLoading.value = false
  }
}

// 显示隐私政策
const showPrivacy = () => {
  alert('我们重视您的隐私，所有数据都经过加密存储...')
}

// 显示使用条款
const showTerms = () => {
  alert('使用本应用即表示您同意我们的服务条款...')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login-form {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.header {
  text-align: center;
  margin-bottom: 32px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: white;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.login-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-bottom: 24px;
  padding: 4px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px;
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  background: none;
}

.tab-item.active {
  background: white;
  color: #333;
}

.input-group {
  margin-bottom: 20px;
}

.input-label {
  display: block;
  font-size: 14px;
  color: white;
  margin-bottom: 8px;
}

.input-field {
  width: 100%;
  padding: 16px;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 8px;
  font-size: 16px;
  color: #333;
  box-sizing: border-box;
}

.input-field::placeholder {
  color: #999;
}

.password-input {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
  font-size: 14px;
  border: none;
  background: none;
  cursor: pointer;
}

.login-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.2s;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.oauth-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.oauth-btn {
  width: 100%;
  padding: 16px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.oauth-btn .icon {
  margin-right: 8px;
  font-size: 18px;
}

.oauth-btn.wechat {
  background: #07C160;
  color: white;
}

.oauth-btn.alipay {
  background: #1677FF;
  color: white;
}

.oauth-btn.douyin {
  background: #FE2C55;
  color: white;
}

.oauth-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.oauth-tip {
  text-align: center;
  margin-top: 16px;
}

.oauth-tip p {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.actions {
  text-align: center;
  margin-top: 16px;
}

.link {
  color: white;
  font-size: 14px;
  text-decoration: underline;
  background: none;
  border: none;
  cursor: pointer;
}

.footer {
  margin-top: 32px;
  text-align: center;
}

.version {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  margin-bottom: 8px;
}

.links .link {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  margin: 0 4px;
}

.separator {
  color: rgba(255, 255, 255, 0.6);
  margin: 0 8px;
}

.hint {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.error-hint {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #ff4d4f;
}

.success-hint {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #52c41a;
}

.register-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 8px;
}

.register-form::-webkit-scrollbar {
  width: 6px;
}

.register-form::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.register-form::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.register-form::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>